<template>
  <div class="">
    <!-- <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品添加</el-breadcrumb-item>
    </el-breadcrumb> -->
    <crumb  title="首页" title2="商品管理" title3="商品添加"></crumb >
    <el-card class="box-card">
      <el-alert
        title="消息提示的文案"
        type="info"
        center
        show-icon
        :closable="false"
        style="margin: 10px 0px"
      >
      </el-alert>
      <el-steps
        :active="active - 0"
        align-center
        :space="200"
        finish-status="success"
        class="el-steps"
      >
        <el-step title="基本信息 "></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <el-form
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
        ref="ruleForm"
        :label-position="labelPosition"
      >
        <el-tabs
          tab-position="left"
          v-model="active"
          :before-leave="beforeTable"
          @tab-click="tabclick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="ruleForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="价格" prop="goods_price">
              <el-input v-model="ruleForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="数量" prop="goods_number">
              <el-input v-model="ruleForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="重量" prop="goods_weight">
              <el-input v-model="ruleForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="分类" prop="goods_cat">
              <el-cascader
                v-model="ruleForm.goods_cat"
                :options="options"
                :props="cateProps"
                @change="handleChange"
                style="width: 100%"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              :key="item.attr_id"
              v-for="item in manyTable"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="cb"
                  v-for="(cb, i) in item.attr_vals"
                  :key="i"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item v-for="item in onlyTable" :label="item.attr_name" :key="item.index">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              action="http://122.112.253.28:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :headers="headersObj"
              :file-list="fileList"
              :on-success="handlSuccess"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor
              v-model="ruleForm.goods_introduce"
              style="height: 200px"
            ></quill-editor>
            <div style="margin-top: 80px">
              <el-button type="primary" @click="updagoods">确定</el-button>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
      <img :src="previewPath" class="previewImg" style="width: 100%" />
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    return {
      labelPosition: "top",
      fileList: [],
      headersObj: {
        Authorization: localStorage.getItem("token"),
      },
      manyTable: [],
      onlyTable: [],
      active: 0,
      ruleForm: {
        goods_name: "",
        goods_cat: [],
        goods_price: "",
        goods_number: "",
        goods_weight: "",
        goods_introduce: "",
        pics: [],
        attrs: [],
      },
      options: [],
      cateProps: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id",
        children: "children",
      },
      rules: {
        goods_name: [
          { required: true, message: "请输入名称", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" },
        ],
        goods_cat: [{ required: true, message: "请选择活动区域", trigger: "change" }],
      },
      previewPath: "", //图片地址
      previewVisible: false,
    };
  },
  //监听属性 类似于data概念
  computed: {
    cateId() {
      if (this.ruleForm.goods_cat.length === 3) {
        return this.ruleForm.goods_cat[2];
      }
      return null;
    },
  },
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    beforeTable(activeName, oldActivName) {
      if (oldActivName === "0" && this.ruleForm.goods_cat.length !== 3) {
        this.$message.error("请填写完整");
        return false;
      }
    },
    //确定
    updagoods() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) {
          return this.$message.error("请填写完整");
        }
        this.ruleForm.goods_cat = this.ruleForm.goods_cat.join(",");
        this.manyTable.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(" "),
          };
          this.ruleForm.attrs.push(newInfo);
        });
        this.onlyTable.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          };
          this.ruleForm.attrs.push(newInfo);
        });
        // console.log(this.ruleForm);
        const { data: res } = await this.myaxios.put(
          `goods/${this.$route.query.id}`,
          this.ruleForm
        );
        console.log(res)
        this.$message.success("成功");
        this.$router.push({ path: "/goods" });
      });
    },
    //图片上传成功
    handlSuccess(response) {
      console.log(response);
      const picsInfo = { pics: response.data.tmp_path };
      this.ruleForm.pics.push(picsInfo);
    },
    //删除图片
    handleRemove(file) {
      const filtPath = file.response.data.tmp_path;
      const i = this.ruleForm.pics.findIndex((x) => x.pic == filtPath);
      this.ruleForm.pics.splice(i, 1);
    },
    //查看图片
    handlePreview(file) {
      //   console.log(file);
      this.previewPath = file.response.data.url;
      this.previewVisible = true;
    },
    async tabclick() {
      if (this.active === "1") {
        const { data: res } = await this.myaxios.get(
          `categories/${this.cateId}/attributes?sel=many`
        );
        console.log(res);
        res.data.forEach((item) => {
          item.attr_vals = item.attr_vals.split(" ");
        });
        this.manyTable = res.data;
        // console.log(this.manyTable);
      } else if (this.active === "2") {
        const { data: res } = await this.myaxios.get(
          `categories/${this.cateId}/attributes?sel=only`
        );
        // console.log(res);
        this.onlyTable = res.data;
        // console.log(this.onlyTable);
      }
    },

    async addSer() {
      const { data: res } = await this.myaxios.get("categories");
      // console.log(res);
      this.options = res.data;
    },
    handleChange() {},
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  async created() {
    this.addSer();
    const { data: res } = await this.myaxios.get(`goods/${this.$route.query.id}`);
    this.ruleForm = res.data;
    console.log(res);
    this.ruleForm.goods_cat = this.ruleForm.goods_cat.split(",");
    var arr = [];
    this.ruleForm.goods_cat.forEach((item) => {
      item = parseInt(item);
      arr.push(item);
    });
    this.ruleForm.goods_cat = arr;
    this.ruleForm.pics.map((item) => {
      this.fileList.push({
        url: item.pics_sma_url,
      });
    });
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped>
.box-card {
  padding: 20px;
  height: 100%;
}
.el-steps {
  margin: 15px 0;
}
</style>
